<template>
  <div class="user-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增用户
            </el-button>
            <el-button type="success" :disabled="selectedUsers.length === 0" @click="handleBatchExport">
              <el-icon><Download /></el-icon>
              导出选中
            </el-button>
            <el-upload
              action="#"
              :show-file-list="false"
              :before-upload="handleBatchImport"
              accept=".xlsx,.xls"
              style="display: inline-block; margin-left: 10px;"
            >
              <el-button type="warning">
                <el-icon><Upload /></el-icon>
                批量导入
              </el-button>
            </el-upload>
          </div>
        </div>
      </template>

      <!-- 高级搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable @clear="handleSearch" @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="searchForm.realName" placeholder="请输入真实姓名" clearable @clear="handleSearch" @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable @clear="handleSearch" @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable @clear="handleSearch" @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable @clear="handleSearch" @change="handleSearch">
            <el-option label="全部" value="" />
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.createTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 批量操作工具栏 -->
      <div class="batch-toolbar" v-if="selectedUsers.length > 0">
        <span>已选择 {{ selectedUsers.length }} 项</span>
        <el-button type="danger" size="small" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button type="warning" size="small" @click="handleBatchDisable">
          <el-icon><CircleClose /></el-icon>
          批量禁用
        </el-button>
        <el-button type="success" size="small" @click="handleBatchEnable">
          <el-icon><CircleCheck /></el-icon>
          批量启用
        </el-button>
      </div>

      <el-table 
        :data="userList" 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column prop="lastLoginTime" label="最后登录时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button 
              :type="row.status === 1 ? 'danger' : 'success'" 
              link 
              @click="handleToggleStatus(row)"
            >
              <el-icon><component :is="row.status === 1 ? Lock : Unlock" /></el-icon>
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pageInfo.pageNum"
        v-model:page-size="pageInfo.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" maxlength="20" show-word-limit :disabled="!!userForm.id">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" maxlength="30" show-word-limit />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" maxlength="11" show-word-limit />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="userForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
          <span class="status-tips" :class="userForm.status === 1 ? 'status-enable' : 'status-disable'">
            {{ userForm.status === 1 ? '用户可正常登录系统' : '用户无法登录系统' }}
          </span>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="userForm.roleIds" multiple placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Refresh, Plus, Download, Upload, Delete, User, CircleClose, CircleCheck, Lock, Unlock } from '@element-plus/icons-vue'
import { getUserList, createUser, updateUser, deleteUser, updateUserStatus, getRoleList } from '@/api/system'
import type { User, Role } from '@/types/api'
import * as XLSX from 'xlsx'

const loading = ref(false)
const userList = ref<User[]>([])
const total = ref(0)
const selectedUsers = ref<User[]>([])
const roleList = ref<Role[]>([])

const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10
})

// 高级搜索表单
const searchForm = reactive({
  username: '',
  realName: '',
  email: '',
  phone: '',
  status: '' as number | '',
  createTimeRange: [] as string[]
})

const dialogVisible = ref(false)
const submitLoading = ref(false)
const userFormRef = ref<FormInstance>()

const userForm = reactive({
  id: undefined as number | undefined,
  username: '',
  realName: '',
  email: '',
  phone: '',
  status: 1,
  roleIds: [] as number[]
})

const userRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 30, message: '真实姓名长度应在2-30个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  roleIds: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

const dialogTitle = computed(() => 
  userForm.id ? '编辑用户' : '新增用户'
)

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const response = await getRoleList()
    roleList.value = response
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  }
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pageInfo.pageNum,
      pageSize: pageInfo.pageSize,
      ...searchForm,
      status: searchForm.status === '' ? undefined : searchForm.status,
      startTime: searchForm.createTimeRange?.[0],
      endTime: searchForm.createTimeRange?.[1]
    }
    const response = await getUserList(params)
    userList.value = response.records || response
    total.value = response.total || response.length
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索功能
const handleSearch = () => {
  pageInfo.pageNum = 1
  fetchUserList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    realName: '',
    email: '',
    phone: '',
    status: '',
    createTimeRange: []
  })
  handleSearch()
}

// 表格选择变化
const handleSelectionChange = (selection: User[]) => {
  selectedUsers.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
      '批量删除确认',
      { type: 'warning' }
    )
    
    const userIds = selectedUsers.value.map(user => user.id)
    // 这里需要后端支持批量删除API
    for (const userId of userIds) {
      await deleteUser(userId)
    }
    
    ElMessage.success('批量删除成功')
    selectedUsers.value = []
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 批量启用
const handleBatchEnable = async () => {
  try {
    const userIds = selectedUsers.value.map(user => user.id)
    // 这里需要后端支持批量启用API
    for (const userId of userIds) {
      await updateUserStatus(userId, 1)
    }
    
    ElMessage.success('批量启用成功')
    selectedUsers.value = []
    fetchUserList()
  } catch (error) {
    ElMessage.error('批量启用失败')
  }
}

// 批量禁用
const handleBatchDisable = async () => {
  try {
    const userIds = selectedUsers.value.map(user => user.id)
    // 这里需要后端支持批量禁用API
    for (const userId of userIds) {
      await updateUserStatus(userId, 0)
    }
    
    ElMessage.success('批量禁用成功')
    selectedUsers.value = []
    fetchUserList()
  } catch (error) {
    ElMessage.error('批量禁用失败')
  }
}

// 批量导出
const handleBatchExport = () => {
  try {
    const exportData = selectedUsers.value.map(user => ({
      用户名: user.username,
      真实姓名: user.realName,
      邮箱: user.email,
      手机号: user.phone,
      状态: user.status === 1 ? '启用' : '禁用',
      创建时间: user.createTime,
      最后登录时间: user.lastLoginTime
    }))
    
    const ws = XLSX.utils.json_to_sheet(exportData)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '用户数据')
    XLSX.writeFile(wb, `用户数据_${new Date().toLocaleDateString()}.xlsx`)
    
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 批量导入
const handleBatchImport = (file: File) => {
  const reader = new FileReader()
  reader.onload = async (e) => {
    try {
      const data = new Uint8Array(e.target?.result as ArrayBuffer)
      const workbook = XLSX.read(data, { type: 'array' })
      const sheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[sheetName]
      const jsonData = XLSX.utils.sheet_to_json(worksheet)
      
      // 这里需要处理导入数据的格式验证和批量创建
      ElMessage.success(`成功读取 ${jsonData.length} 条数据`)
      // 实际导入逻辑需要根据后端API实现
    } catch (error) {
      ElMessage.error('文件解析失败')
    }
  }
  reader.readAsArrayBuffer(file)
  return false // 阻止自动上传
}

const handleAdd = () => {
  userForm.id = undefined
  userForm.username = ''
  userForm.realName = ''
  userForm.email = ''
  userForm.phone = ''
  userForm.status = 1
  userForm.roleIds = []
  dialogVisible.value = true
}

const handleEdit = (row: User) => {
  userForm.id = row.id
  userForm.username = row.username
  userForm.realName = row.realName
  userForm.email = row.email
  userForm.phone = row.phone
  userForm.status = row.status
  userForm.roleIds = row.roleIds || []
  dialogVisible.value = true
}

const handleToggleStatus = async (row: User) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '禁用' : '启用'}用户"${row.username}"吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await updateUserStatus(row.id, row.status === 1 ? 0 : 1)
    ElMessage.success(`${row.status === 1 ? '禁用' : '启用'}成功`)
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleDelete = async (row: User) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${row.username}"吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await deleteUser(row.id)
    ElMessage.success('删除成功')
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    submitLoading.value = true
    
    // 检查用户名是否已存在（新增时）
    if (!userForm.id) {
      const existingUser = userList.value.find(user => user.username === userForm.username)
      if (existingUser) {
        ElMessage.error('用户名已存在')
        return
      }
    }
    
    if (userForm.id) {
      await updateUser(userForm.id, userForm)
      ElMessage.success('更新成功')
    } else {
      await createUser(userForm)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  userFormRef.value?.resetFields()
}

const handleSizeChange = (val: number) => {
  pageInfo.pageSize = val
  fetchUserList()
}

const handleCurrentChange = (val: number) => {
  pageInfo.pageNum = val
  fetchUserList()
}

onMounted(() => {
  fetchRoleList()
  fetchUserList()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.batch-toolbar {
  margin-bottom: 15px;
  padding: 10px 15px;
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 15px;
}

@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .batch-toolbar {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>